package com.contain.auth.security.config;

import com.contain.auth.config.CustomerJwtAccessTokenConverter;
import com.contain.auth.config.InformationTokenEnhancer;
import com.contain.auth.config.redis.JMonkeyJwtAccessTokenConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * code换token 401 https://blog.csdn.net/u012040869/article/details/80140515/
 * @Auther: tianchao
 * @Date: 2021/7/3 22:16
 * @Description:
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
    /**
     * 密码模式需要的认证管理
     */
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private DataSource dataSource;



    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 客户端信息从数据库加载
     * 授权码模式
     *         //http://localhost:8901/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://www.baidu.com&scope=all
     * 密码模式
     *      http://localhost:8901/oauth/token?grant_type=password&scope=all&client_id=client&client_secret=123123&username=tianchao&password=123456
     *  @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        clients.withClientDetails(clientDetailsService);
    }

    /**
     * 配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(new InformationTokenEnhancer());
        delegates.add(customerJwtAccessTokenConverter());
        enhancerChain.setTokenEnhancers(delegates);
        endpoints.authenticationManager(authenticationManager) //使用密码模式需要配置
                .tokenStore(tokenStore())  //指定token存储到redis
                .tokenEnhancer(enhancerChain)
                // refresh token有两种使用方式：重复使用(true)、非重复使用(false)，默认为true
                //      1 重复使用：access token过期刷新时， refresh token过期时间未改变，仍以初次生成的时间为准
                //      2 非重复使用：access token过期刷新时， refresh token过期时间延续，在refresh token有效期内刷新便永不失效达到无需再次登录的目的
                .reuseRefreshTokens(true)  //refresh_token是否重复使用
                // .userDetailsService(userService) //刷新令牌授权包含对用户信息的检查
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST); //支持GET,POST请求
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证
        security.allowFormAuthenticationForClients()
                // 配置校验token需要带入clientId 和clientSeret配置
                //.checkTokenAccess("isAuthenticated()");
        .checkTokenAccess("permitAll()");
    }

    /**
     * 配置token存储，这个配置token存到redis中,还有一种常用的是JwkTokenStore
     * jwt的缺点已发布令牌不可控
     * @return
     */
    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        //redisTokenStore.setSerializationStrategy(new FastjsonRedisTokenStoreSerializationStrategy());
        return redisTokenStore;
    }

    /**
     * 使用非对称加密算法对token签名
     * @return
     */
    @Bean
    public JwtAccessTokenConverter customerJwtAccessTokenConverter(){
        return new CustomerJwtAccessTokenConverter();
    }

    /**
     * keytool -genkey -alias jwt -keyalg RSA -keypass 123456 -keystore jwt.jks -storepass 123456
     * -alias 别名
     * -keyalg 密钥算法
     * -keypass 密钥口令
     * -keystore 生成密钥库的存储路径和名称
     * -storepass 密钥库口令
     * https://github.com/hxrui/youlai-mall/issues/27
     *  /**
     *  openssl也要安装，
     * 下载地址 http://slproweb.com/products/Win32OpenSSL.html
     * 环境变量path中配置openssl安装路径，如：C:\OpenSSL-Win64\bin
     *  **
     * keytool -list -rfc --keystore jwt.jks | openssl x509 -inform pem -pubkey
     * @return
     */
    @Bean
    public KeyPair keyPair() {
        //从classpath下的证书中获取秘钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", "123456".toCharArray());
    }
}
